package com.itheima.aspect;

import com.itheima.annotation.AutoFill;
import com.itheima.constant.AutoFillConstant;
import com.itheima.enumeration.OperationDateType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * @projectName: kafka
 * @package: com.itheima.aspect
 * @className: AutoFillAspect
 * @author: Eric
 * @description: TODO
 * @date: 2023/9/21 10:14
 * @version: 1.0
 */
@Slf4j
@Component
@Aspect
public class AutoFillAspect {

    @Pointcut("@annotation(com.itheima.annotation.AutoFill)")
    public void pt(){

    }

    @Before("pt()")
    public void autoFill(JoinPoint joinPoint){
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        OperationDateType operationDateType = autoFill.value();

        try {
            // 2.动态获取入参,进行反射赋值
            Object arg = joinPoint.getArgs()[0];
            if (OperationDateType.INSERT == operationDateType){
                // 用反射获取对象的方法,然后进行动态赋值
                Method setCreatTime = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_DATE, LocalDateTime.class);
                Method setUpdateTime = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_DATE, LocalDateTime.class);

                setCreatTime.invoke(arg,LocalDateTime.now());
                setUpdateTime.invoke(arg,LocalDateTime.now());
            }

            if (OperationDateType.UPDATE == operationDateType){
                Method setUpdateTime = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_DATE, LocalDateTime.class);

                setUpdateTime.invoke(arg,LocalDateTime.now());
            }
        } catch (Exception e) {
            log.info("动态注入属性失败!");
        }
    }
}
